<template>
  <div>
    <el-dialog
      :title="mode==='add'?'新增桌台':'编辑桌台'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="750px"
      @close="close"
    >
      <div>
        <el-form
          ref="form"
          v-loading="loading"
          :model="form"
          :rules="rules"
          size="small"
          label-width="100px"
        >
          <el-form-item label="所属区域：" prop="areaId">
            <el-select v-model="form.areaId" filterable clearable placeholder="请选择">
              <el-option
                v-for="item in areaIdOptions"
                :key="item.value"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button icon="el-icon-plus" size="small" circle @click.prevent="addArea('add')" />
          </el-form-item>
          <el-form-item
            v-if="mode==='edit'||mode==='add'&&type==='single'"
            label="桌台名称："
            prop="tableNo"
          >
            <el-input
              v-model.trim="form.tableNo"
              maxlength="20"
              placeholder="请输入桌台名称"
              show-word-limit
              class="input_430"
            />
          </el-form-item>
          <div v-if="mode==='add'&&type==='batch'">
            <el-form-item label="桌台序号：" style="marginBottom: 0">
              <el-form-item :rules="rules.number" style="display: inline-block" prop="start">
                <el-input
                  v-model.trim="form.start"
                  placeholder="请输入正整数"
                  maxlength="8"
                  class="input_200"
                />
              </el-form-item>&nbsp;&nbsp;至&nbsp;&nbsp;
              <el-form-item :rules="rules.number" style="display: inline-block" prop="end">
                <el-input
                  v-model.trim="form.end"
                  placeholder="请输入正整数"
                  maxlength="8"
                  class="input_200"
                />
              </el-form-item>&nbsp;&nbsp;
              <el-checkbox v-model="isPrefix0">补全位数</el-checkbox>
            </el-form-item>
            <el-form-item label="桌台前缀：" prop="prefix">
              <el-input v-model.trim="form.prefix" class="input_200" placeholder="请输入前缀" />
            </el-form-item>
            <el-form-item label="桌台后缀：" prop="suffix">
              <el-input v-model.trim="form.suffix" class="input_200" placeholder="请输入后缀" />
            </el-form-item>
            <el-form-item label="桌台预览：" prop="tableNo">
              <el-card :body-style="{ 'padding-bottom': '0px' }" class="nest-card-box">
                <el-input
                  v-model="form.tableNo"
                  :autosize="{ minRows: 3, maxRows: 10}"
                  type="textarea"
                />
                <div>一行对应一个桌台名(可通过Enter换行)，单次最多支持99个</div>
              </el-card>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button :disabled="loading" size="small" round type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑 -->
    <dialog-edit-area ref="editArea" />
  </div>
</template>

<script>
import DialogEditArea from './DialogEditArea'
import { validateCustomPositiveInt } from '@/utils/validate'
import { saveTableNumber, getTableAreasList } from '../../../api/table'
import { prefix0Integer } from '@/utils'
export default {
  components: {
    DialogEditArea
  },
  props: {
    areaIdOptions: {
      type: Array,
      required: true
    },
    shopId: {
      type: Number,
      required: true
    }
  },
  data() {
    /**
     * 表单校验方法相关
     */
    const validateNumber = (rule, value, callback) => {
      if (value && !validateCustomPositiveInt(value, 8, [0])) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }

    const validateTableNo = (rule, value, callback) => {
      if (
        this.mode === 'edit' ||
        (this.mode === 'add' && this.type === 'single')
      ) {
        if (value === '') {
          callback(new Error('请输入桌台名称'))
        } else {
          callback()
        }
      } else if (value === '') {
        callback(new Error('请至少录入一个桌台名称'))
      } else {
        const arr = this.form.tableNo
          .trim()
          .replace(/\ */g, '')
          .replace(/\n/g, ',')
          .replace(/,+/g, ',')
          .split(',')
        const len = arr.length
        const result = arr.some((v, i) => v.length > 20)
        if (len > 99) callback(new Error('单次最多支持99个'))
        result
          ? callback(new Error('单个桌台名称长度不超过20个字'))
          : callback()
      }
    }

    return {
      /**
       * 表单校验字段相关
       */
      rules: {
        // 前后缀
        number: [
          {
            validator: validateNumber
          }
        ],
        // 桌台名称
        tableNo: [
          {
            required: true,
            validator: validateTableNo
          }
        ],
        // 名称
        areaId: [
          {
            required: true,
            message: '请选择所属区域',
            trigger: ['change']
          }
        ]
      },
      resolve: null,
      reject: null,
      // 状态
      loading: false,
      dialogVisible: null,
      // 数据
      mode: 'add',
      type: 'single',
      isPrefix0: false,
      form: {
        start: '',
        end: '',
        prefix: '',
        suffix: '',
        areaId: '',
        shopId: '',
        tableNo: ''
      }
    }
  },
  computed: {
    tableName() {
      const { start, end, prefix, suffix } = this.form
      return { start, end, prefix, suffix, isPrefix0: this.isPrefix0 }
    }
  },
  watch: {
    tableName() {
      if (this.mode === 'add' && this.type === 'batch') {
        if (
          /^(([1-9]\d{0,7})|0)$/.test(this.form.start) &&
          /^(([1-9]\d{0,7})|0)$/.test(this.form.end) &&
          this.form.end - this.form.start >= 0
        ) {
          this.form.tableNo = ''
          const maxNum =
            this.form.end - this.form.start > 98
              ? Number(this.form.start) + 98
              : this.form.end
          for (let index = this.form.start; index <= maxNum; index++) {
            const num = this.isPrefix0
              ? prefix0Integer(index, maxNum.toString().length)
              : index
            this.form.tableNo +=
              this.form.prefix + num + this.form.suffix + '\n'
          }
        } else {
          this.form.tableNo = ''
        }
      }
    }
  },
  methods: {
    open({ mode = 'add', row = '', type = '' }) {
      this.mode = mode
      this.type = type
      if (mode === 'add') this.form.shopId = this.shopId
      if (mode === 'edit') this.form = Object.assign({}, row)
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.form = {
        start: '',
        end: '',
        prefix: '',
        suffix: '',
        areaId: '',
        shopId: '',
        tableNo: ''
      }
      this.loading = false
      this.$refs.form.resetFields()
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 按钮组
     */
    // 点击新增区域
    addArea(type, row = '') {
      this.$refs.editArea.open(type, this.form.shopId, row).then(res => {
        this.$emit('getTableAreasOptions')
      })
    },

    // 保存
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const params = Object.assign({}, this.form)
          params.tableNo = params.tableNo
            .trim()
            .replace(/\ */g, '')
            .replace(/\n/g, ',')
            .replace(/,+/g, ',')
            .split(',')
          const tableArr = []
          params.tableNo.map(v => {
            const obj = {
              areaId: params.areaId,
              areaName: params.areaId,
              shopId: params.shopId,
              tableNo: v
            }
            if (params.id) obj.id = params.id
            tableArr.push(obj)
          })
          console.log(tableArr)
          this.loading = true
          saveTableNumber(tableArr)
            .then(res => {
              this.$notify({
                title: '成功',
                message: '保存桌号成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.resolve()
              this.hide()
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-select {
  width: 430px;
  margin-right: 10px;
}
.input_430 {
  width: 430px;
}
.input_200 {
  width: 200px;
}
.input_400 {
  width: 400px;
}
/* 内层嵌套卡片 */
.nest-card-box {
  margin-bottom: 10px;
}
</style>
